<template>
  <div class="form-container">
    <el-form inline :model="form" ref="refForm" class="form-line" label-width="90">
      <el-form-item label="姓名/手机号" prop="fullName">
        <el-input size="default" @keydown.enter="getList" v-model="form.fullName" placeholder="姓名/手机号"></el-input>
      </el-form-item>
    </el-form>
    <div class="btn-container">
      <el-button type="primary" @click="handleRest(refForm as FormInstance)">重置</el-button>
      <el-button type="primary" @click="hadleSearch">查询</el-button>
      <el-button type="primary" @click="handleAdd">添加订单分拣员</el-button>
    </div>
  </div>
  <div class="table-container">
    <el-table
      border
      :cell-style="{ textAlign: 'center', fontSize: '13px' }"
      :header-cell-style="{
        textAlign: 'center',
        fontWeight: '100',
        fontSize: '13px',
        color: 'white',
        backgroundColor: '#009688'
      }"
      style="width: 100%"
      :data="list"
    >
      <el-table-column fixed prop="fullName" label="姓名" />
      <el-table-column prop="phonenumber" label="手机号" />
      <el-table-column prop="status" label="状态">
        <template #default="scope">
          <el-switch v-model="scope.row.status" :active-value="1" :inactive-value="0"></el-switch>
        </template>
      </el-table-column>
      <el-table-column prop="createTime" label="创建时间" />
      <el-table-column fixed="right" label="操作">
        <template #default="scope">
          <el-button type="primary" size="small" link @click="handleDelete(scope.row)">删除</el-button>
          <el-button type="primary" size="small" link @click="handleUpdate(scope.row)">修改</el-button>
          <el-button type="primary" size="small" link @click="handleUpdatePhone(scope.row)">修改手机号</el-button>
        </template>
      </el-table-column>
    </el-table>
    <div class="pagination-container">
      <el-pagination background size="small" layout="prev, pager, next" @change="getList" :total="pageTotal" :page-size="10" />
    </div>
  </div>
  <el-dialog v-model="addVisible" :title="titleMsg" width="500" center>
    <div>
      <el-form :model="editParams" ref="editRefForm" :rules="editRules" label-width="100">
        <el-form-item prop="fullName" label="姓名">
          <el-input v-model="editParams.fullName" placeholder="姓名"></el-input>
        </el-form-item>
        <el-form-item prop="phonenumber" label="手机号">
          <el-input v-model="editParams.phonenumber" placeholder="请填写新手机号"></el-input>
        </el-form-item>
        <el-form-item prop="smsCode" label="验证码">
          <el-input v-model="editParams.smsCode" placeholder="请填写短信验证码"></el-input>
          <span class="sms-code"
            ><el-button type="text" :disabled="codeTime > 0" @click="handleGetSmsCode">{{
              codeTime > 0 ? `${codeTime}秒后重新获取` : "获取验证码"
            }}</el-button></span
          >
        </el-form-item>
      </el-form>
    </div>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="addVisible = false">取消</el-button>
        <el-button type="primary" @click="handleEditSubmit(editRefForm as FormInstance)"> 确认 </el-button>
      </div>
    </template>
  </el-dialog>
  <el-dialog v-model="centerDialogVisible" title="修改手机号" width="500" center>
    <div>
      <el-form :model="updatePhoneForm" ref="refPhoneForm" :rules="updatePhoneFormRules" label-width="100">
        <el-form-item prop="oldPhonenumber" label="旧手机号">
          <el-input v-model="updatePhoneForm.oldPhonenumber" disabled placeholder=""></el-input>
        </el-form-item>
        <el-form-item prop="phoneNo" label="新手机号">
          <el-input v-model="updatePhoneForm.phoneNo" placeholder="请填写新手机号"></el-input>
        </el-form-item>
        <el-form-item prop="smsCode" label="新手机验证码">
          <el-input v-model="updatePhoneForm.smsCode" placeholder="请填写短信验证码"></el-input>
          <span class="sms-code"
            ><el-button type="text" :disabled="codeTime > 0" @click="handleGetSmsCode2">{{
              codeTime > 0 ? `${codeTime}秒后重新获取` : "获取验证码"
            }}</el-button></span
          >
        </el-form-item>
      </el-form>
    </div>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="centerDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleUpdatePhoneSubmit(refPhoneForm as FormInstance)"> 确认 </el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup lang="tsx" name="useProTable">
import { Sorter } from "@/api/interface/city/citySorter";
import {
  addSorterAPI,
  deleteSorterAPI,
  editSorterAPI,
  getSorterListAPI,
  updatePhoneAPI
} from "@/api/modules/city/citySorter/api";
import { ElMessage, ElMessageBox, FormInstance, FormRules } from "element-plus";
import { onMounted, ref } from "vue";
let pageTotal = ref<number>(0);
let codeTime = ref<number>(0);
const form = ref<Sorter.SearchParams>({
  fullName: "",
  auditStatus: "0",
  delFlag: "",
  province: JSON.parse(localStorage.getItem("userInfo") as string).province,
  city: JSON.parse(localStorage.getItem("userInfo") as string).city,
  pageNum: 1,
  pageSize: 10
});
const refForm = ref<FormInstance>();

// 编辑模块
const editRefForm = ref<FormInstance>();
const editRules = ref<FormRules>({
  fullName: [{ required: true, message: "请填写姓名", trigger: "blur" }],
  phonenumber: [{ required: true, message: "请填写手机号", trigger: "blur" }],
  smsCode: [{ required: true, message: "请填写短信验证码", trigger: "blur" }]
});
let editParams = ref<Sorter.EditParams>({
  province: JSON.parse(localStorage.getItem("userInfo") as string).province,
  city: JSON.parse(localStorage.getItem("userInfo") as string).city
});
const handleEditSubmit = (formEl: FormInstance) => {
  formEl.validate((valid: boolean) => {
    if (valid) {
      // 发送请求
      titleMsg.value == "添加" ? addSorter() : editSorter();
      // 关闭弹窗
    } else {
      ElMessage.error("请检查输入项");
    }
  });
};
const addSorter = async () => {
  // 发送请求
  const { code, msg } = await addSorterAPI(editParams.value);
  if (code == "200") {
    ElMessage.success("添加成功");
    addVisible.value = false;
    getList();
  } else {
    ElMessage.error(`添加失败,${msg}`);
  }
};
const handleUpdate = (row: Sorter.Row) => {
  editParams.value = {
    userId: row.userId,
    fullName: row.fullName,
    phonenumber: row.phonenumber,
    province: row.province,
    city: row.city,
    status: row.status
  };
  addVisible.value = true;
  titleMsg.value = "修改";
};
const editSorter = async () => {
  // 发送请求
  const { code, msg } = await editSorterAPI(editParams.value);
  if (code == "200") {
    ElMessage.success("修改成功");
    addVisible.value = false;
    getList();
  } else {
    ElMessage.error(`修改失败,${msg}`);
  }
};

// 添加模块
const addVisible = ref<boolean>(false);
const titleMsg = ref<string>("添加");
const list = ref<Sorter.Row[]>([]);
const handleRest = (formEl: FormInstance) => {
  formEl.resetFields();
  form.value.pageNum = 1;
  getList();
};
const handleAdd = () => {
  if (editParams.value.userId) {
    delete editParams.value.userId;
  }
  addVisible.value = true;
  titleMsg.value = "添加";
};
const hadleSearch = () => {
  getList();
};
const getList = async () => {
  const { rows, code, msg, total } = await getSorterListAPI(form.value);
  if (code == "200" && rows) {
    list.value = rows;
    if (total) {
      pageTotal.value = total;
    }
  } else {
    ElMessage.error(`获取失败,${msg}`);
  }
};
// 获取短信验证码
const handleGetSmsCode = () => {
  if (!editParams.value.phonenumber) return ElMessage.error("请填写新手机号");
  codeTime.value = 60;
  let timer = setInterval(() => {
    codeTime.value--;
    if (codeTime.value <= 0) {
      clearInterval(timer);
    }
  }, 1000);
};

// 删除分拣员
const handleDelete = (row: Sorter.Row) => {
  ElMessageBox.confirm(`是否确认删除分拣员【${row.fullName}】?`, "提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning"
  })
    .then(() => {
      deleteSorter(row);
    })
    .catch(() => {
      ElMessage.info("已取消删除");
    });
};
const deleteSorter = async (row: Sorter.Row) => {
  const { code, msg } = await deleteSorterAPI(row.userId);
  if (code == "200") {
    ElMessage.success("删除成功");
    getList();
  } else {
    ElMessage.error(`删除失败,${msg}`);
  }
};

// 修改手机号
const centerDialogVisible = ref<boolean>(false);
const updatePhoneForm = ref<Sorter.UpdatePhoneParams>({
  userId: "",
  phoneNo: "",
  smsCode: ""
});
const refPhoneForm = ref<FormInstance>();
const updatePhoneFormRules = ref<FormRules>({
  phoneNo: [
    { required: true, message: "请输入新手机号", trigger: "blur" },
    { type: "string", message: "请输入正确的手机号", trigger: "blur" }
  ],
  smsCode: [
    { required: true, message: "请输入短信验证码", trigger: "blur" },
    { type: "string", message: "请输入正确的短信验证码", trigger: "blur" }
  ]
});
const handleUpdatePhone = (row: Sorter.Row) => {
  updatePhoneForm.value = {
    userId: row.userId,
    oldPhonenumber: row.phonenumber,
    phoneNo: "",
    smsCode: ""
  };
  centerDialogVisible.value = true;
};
const handleUpdatePhoneSubmit = (elForm: FormInstance) => {
  elForm.validate((valid: boolean) => {
    if (valid) {
      console.log(updatePhoneForm.value);
      // 发送请求
      updatePhoneNumber();
    } else {
      ElMessage.error("请检查输入项");
    }
  });
};
const updatePhoneNumber = async () => {
  // 发送请求
  const { code, msg } = await updatePhoneAPI(updatePhoneForm.value);
  if (code == "200") {
    ElMessage.success("修改成功");
    centerDialogVisible.value = false;
    getList();
  } else {
    ElMessage.error(`修改失败,${msg}`);
  }
};
// 获取短信验证码
const handleGetSmsCode2 = () => {
  if (!updatePhoneForm.value.phoneNo) return ElMessage.error("请填写新手机号");
  codeTime.value = 60;
  let timer = setInterval(() => {
    codeTime.value--;
    if (codeTime.value <= 0) {
      clearInterval(timer);
    }
  }, 1000);
};
onMounted(() => {
  getList();
});
</script>
<style lang="scss" scoped>
.form-container {
  padding: 10px;
  margin-bottom: 10px;
  background-color: white;
  .btn-container {
    display: inline-block;
    float: right;
    vertical-align: middle;
    ::v-deep .el-button > span {
      font-size: 13px;
    }
  }
  .el-form {
    display: inline-block;
    ::v-deep .el-form-item__label {
      font-size: 13px;
    }
  }
  .form-line {
    .el-form-item {
      margin: 0;
      margin-right: 20px;
    }
    .el-input {
      width: 240px;
    }
    .el-select {
      width: 240px;
    }
  }
}
.table-container {
  padding: 40px 10px;
  padding-bottom: 60px;
  background-color: white;
  .pagination-container {
    // display: inline-block;
    float: right;
    margin-top: 20px;
    background-color: white;
  }
}
::v-deep .el-tag--dark {
  margin: 5px;
  cursor: pointer;
}
::v-deep .el-input--suffix .el-input__inner {
  padding-right: 15px;
}
::v-deep .el-form-item__label {
  font-size: 13px;
  font-weight: 100;
  color: black;
}
::v-deep .el-button > span {
  font-size: 13px;
}
::v-deep .el-input__inner {
  font-size: 13px;
}
.sms-code {
  position: absolute;
  right: 5px;
}
</style>
